package com.threeman.mapswaypoints1;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class AzimuthView extends View
{

	private static final String TAG = AzimuthView.class.getSimpleName();

	private Paint mArrowPaint;

	private Bitmap mArrowBitmap;

	private Matrix mArrowMatrix;

	private float mArrowScale = 1.0f;

	private float mRotation = 0.0f;

	public AzimuthView(Context context)
	{
		super(context);
		initializeView();
	}

	public AzimuthView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initializeView();
	}

	public AzimuthView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initializeView();
	}

	public float getArrowScale()
	{
		return mArrowScale;
	}

	public void setArrowScale(float arrowScale)
	{
		this.mArrowScale = arrowScale;
		mArrowMatrix.setScale(mArrowScale, mArrowScale);
	}

	public float getRotation()
	{
		return mRotation;
	}

	public void setRotation(float rotation)
	{
		// rotation = rotation;
		this.mRotation = rotation;
		this.postInvalidate();
	}

	private void initializeView()
	{
		setFocusable(true);

		mArrowPaint = new Paint();
		mArrowPaint.setFilterBitmap(true);
		mArrowBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.szczala);
		mArrowMatrix = new Matrix();
		mArrowMatrix.setScale(mArrowScale, mArrowScale);

	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		// super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		System.out.println("MeasuredWidth: " + widthMeasureSpec + " MeasuredHeight: " + heightMeasureSpec);

		int w = (int) (mArrowBitmap.getWidth() * mArrowScale);
		int h = (int) (mArrowBitmap.getHeight() * mArrowScale);

		int chosenWidth = h * 2;
		int chosenHeight = h * 2;
		setMeasuredDimension(chosenWidth, chosenHeight);
	}

	private void drawArrow(Canvas canvas)
	{
		int x = ((int) (mArrowBitmap.getWidth() * mArrowScale)) / 2;
		int y = ((int) (mArrowBitmap.getHeight() * mArrowScale)) / 2;
		int px = getMeasuredWidth() / 2 - x;
		int py = getMeasuredHeight() / 2;

		canvas.save(Canvas.MATRIX_SAVE_FLAG);

		canvas.translate(px, py / 2);
		float rotation = getRotation();
		canvas.rotate(-rotation, x, y);
		canvas.drawBitmap(mArrowBitmap, mArrowMatrix, mArrowPaint);
		canvas.restore();
	}

	@Override
	protected void onDraw(Canvas canvas)
	{
		// TODO Auto-generated method stub
		// super.onDraw(canvas);
		drawArrow(canvas);

		canvas.restore();
	}
}
